import { defineComponent, h, PropType } from 'vue';
import Style from "./index.module.scss";
import router from "@/router";
import {useBreadcrumbStore} from "@/store/modules/breadcrumb";

/** 按钮 */
export const LdButton = defineComponent({
    props: {
        /** 按钮配色 */
        colors: {
            type: Object as PropType<{ background: string, shadow: string, border: string, FontColor: string }>,
            default: {
                background: '#3973F8',
                shadow: '#1246BC',
                border: '#3973F8',
                FontColor: '#fff'
            }
        },
        /** 图标 */
        icon: {
            type: Object as PropType<() => JSX.Element>,
        },
        /** 路由跳转路径 */
        to: {
            type: String,
            default: ''
        },
        /** 是否是返回按钮 */
        isBack: {
            type: Boolean,
            default: false
        }
    },
    emits: ['click'],
    setup(props, { slots, attrs, emit }) {
        const breadcrumbStore = useBreadcrumbStore(); // 实例化Pinia
        const handleClick = () => {
            setTimeout(() => {
                emit('click');

                // 如果设置了跳转路径，则导航到该路径
                if (props.to && !props.isBack) {
                    router.push(props.to);
                }

                // 如果是返回按钮，则导航到上一级
                if (props.isBack) {
                    //如果当前是“首页（/HomePage）”，不处理（避免数组为空）
                    if (router.currentRoute.value.path === '/HomePage') {
                        return;
                    }
                    // 移除面包屑最后一个标题
                    breadcrumbStore.removeLastTitle();
                    //返回上一级
                    router.back();
                }
            }, 100);
        };
        return () => (<>
            <button onClick={handleClick} {...attrs} class={Style.button} style={{ backgroundColor: props.colors.background, boxShadow: `4px 7px 0 ${props.colors.shadow}`, borderColor: props.colors.border, color: props.colors.FontColor }}>
                {props.icon && h(props.icon)}
                {slots.default?.()}
            </button>
        </>);
    }
})
